package com.wxw.BaseLibrary.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.wxw.BaseLibrary.element.JsonObject;
import com.wxw.BaseLibrary.element.JsonProperty;

/**
 * @author david
 * @date 2020-03-12
 */
public class DefaultItemViewCreator implements IJsonDataItemViewCreator {
    private JsonProperty jsonDataList;
    private JsonProperty jsonSetting;
    private int layoutId;

    public DefaultItemViewCreator(int layoutId, JsonProperty jsonData, JsonProperty jsonSetting) {
        this.layoutId = layoutId;
        this.jsonDataList = jsonData;
        this.jsonSetting = jsonSetting;
    }

    @Override
    public View createView(int position, View convertView, LayoutInflater inflater, JsonObject jsonData) {
        ViewsHelper viewsHelper = null;
        JsonObject jsonObject = jsonDataList.get(position).getObject();
        if (convertView == null){
            convertView = inflater.inflate(layoutId, null);
            viewsHelper = new ViewsHelper();
            for (JsonProperty jsonProperty : jsonSetting.getItems()) {
                viewsHelper.getViewMap().put(jsonProperty.getProperty("key").getValue(),
                        convertView.findViewById(jsonProperty.getProperty("id").getInteger()));
            }
            convertView.setTag(viewsHelper);
        } else {
            viewsHelper = (ViewsHelper)convertView.getTag();
        }
        for (JsonProperty jsonProperty : jsonSetting.getItems()) {
            if (jsonProperty.getProperty("set").getBoolean()) {
                setValue(viewsHelper, jsonProperty.getProperty("key").getValue(),
                        jsonProperty.getProperty("label").getValue(), jsonObject);
            }
        }

        setView(viewsHelper, jsonObject);

        return convertView;
    }

    @Override
    public void setView(ViewsHelper helper, JsonObject jsonItem) {
        for (JsonProperty jsonProperty : jsonSetting.getItems()) {
            if (jsonProperty.getProperty(JsonDataAdapter.SHOW).getBoolean()) {
                String key = jsonProperty.getProperty(JsonDataAdapter.KEY).getValue();
                helper.getViewMap().get(key).setVisibility(canShow(key, jsonItem.getProperty(key))?View.VISIBLE:View.INVISIBLE);
            }
        }
    }

    protected boolean canShow(String key, JsonProperty val) {
        return (val != null && !"".equals(val.getValue()) && !"~".equals(val.getValue()));
    }

    protected void setValue(ViewsHelper viewsHelper, String key, String label, JsonObject jsonObject) {
        ((TextView)viewsHelper.getViewMap().get(key)).setText(label + jsonObject.getProperty(key).getValue());
    }
}